<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //12.字符串判断，输入的自复式是否是有效的数字
        var str = window.prompt("请输入一个字符串:");
        var flag = true;
        var count1 = 0; // -
        var count2 = 0; // .
        var pos1 = -1; // -
        var pos2 = -1; // .
        for (var i = 0; i < str.length; i++) {
            var ch = str.charCodeAt(i);
            document.write(ch + '<br>');
            if (!(ch == 45 || ch == 46 || (ch >= 48 && ch <= 57))) {
                flag = false;
                break;
            }
            if (ch == 45) {
                count1++;
                if (pos1 == -1) {
                    pos1 = i;
                }
                if (count1 > 1) {
                    flag = false;
                    break;
                }
            }

            if (ch == 46) {
                count2++;
                if (pos2 == -1) {
                    pos2 = i;
                }
                if (count2 > 1) {
                    flag = false;
                    break;
                }
            }
        }
        document.write(count1 + ' ' + count2 + ' ' + pos1 + ' ' + pos2 + '<br>');
        if (flag) {
            if (count1 == 1 && count2 == 1) {
                if (!(pos1 == 0 && pos2 > 1)) {
                    flag = false;
                }
            }
            if (count1 == 1 && count2 == 0) {
                if (pos1 != 0) {
                    flag = false;
                }
            }
            if (count1 == 0 && count2 == 1) {
                if (pos2 == 0) {
                    flag = false;
                }
            }
            if (count1 == 0 && count2 == 0) {
                flag = true;
            }

        }
        if (flag) {
            // 000123  -000.236  00.123排除这种情况  从负号后一位开始判断，如果是0，判断下一位（前提下一位存在），如果是数字，就false，是.可以
            if (str.charCodeAt(pos1 + 1) == 48 && str.length - 1 > pos1 + 1 && str.charCodeAt(pos1 + 2) != 46) {
                document.write(str + '不可转为数字');
            }
            else {
                document.write(str + '可转为数字');
            }
        } else {
            document.write(str + '不可转为数字');
        }

    </script>
</body>

</html>